package com.kukudb.asaproject.filter;


import com.kukudb.asaproject.pojo.ResponseMessage;
import com.kukudb.asaproject.utils.JWTUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;


@WebFilter(urlPatterns = {"/api/server/*"})
public class IsLoginFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(IsLoginFilter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String ip = request.getRemoteAddr();
        logger.info("IsLoginFilter: " + ip);
        request.getSession().setAttribute("IP",  ip);
        String token = (String) request.getSession().getAttribute("token");
        if (token == null) {
            logger.info("用户未登录");
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.getWriter().write(new ResponseMessage(401, "用户未登录").toJson());
            return;
        }else{
            Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
            logger.info("--session token: " + stringObjectMap);
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
